<template>
	<view>
		<uv-navbar leftText="返回" autoBack="true" title="首次使用" @leftClick="leftClick"></uv-navbar>
		<RxLogo></RxLogo>
		
		<view v-if="hand">
			<!-- <uv-text text="1、医生可以扫码加入诊所，也可以/手动填写诊所信息及手机号等信息新创建诊所。"></uv-text>
			<uv-text text="2、为避免有捣乱者，护士和电手必须通过扫码的方式加入诊所"></uv-text>
			<uv-text text="3、患者首次使用扫码/手动填写诊所信息/手机号的页面"></uv-text> -->
			
			<view class="form_class">
				<view class="input_class"><uv-input border="bottom" v-model="pointsInfo.clinic"><template v-slot:prefix>
					<uv-text text="诊所名称" margin="0 3px 0 0" type="tips"></uv-text></template>
				</uv-input></view>
				<view class="input_class"><uv-input border="bottom" v-model="pointsInfo.name"><template v-slot:prefix>
					<uv-text text="医生名称" margin="0 3px 0 0" type="tips"></uv-text></template>
				</uv-input></view>
				<view class="input_class"><uv-input border="bottom" v-model="pointsInfo.mobile" type="number" maxlength="11"><template v-slot:prefix>
					<uv-text text="医生电话" margin="0 3px 0 0" type="tips"></uv-text></template>
				</uv-input></view>
				
				<view class="input_class">
					<uv-row justify="space-between" gutter="10" @click="PickerClick">
						<uv-col span="4">
							<uv-input border="bottom" v-model="pointsInfo.addressProvince" disabled disabledColor="ffffff"><template v-slot:prefix>
								<uv-text text="省" margin="0 3px 0 0" type="tips"></uv-text></template>
							</uv-input>
						</uv-col>
						<uv-col span="4">
							<uv-input border="bottom" v-model="pointsInfo.addressCity" disabled disabledColor="ffffff"><template v-slot:prefix>
								<uv-text text="市" margin="0 3px 0 0" type="tips"></uv-text></template>
							</uv-input>
						</uv-col>
						<uv-col span="4">
							<uv-input border="bottom" v-model="pointsInfo.addressCounty" disabled disabledColor="ffffff"><template v-slot:prefix>
								<uv-text text="县" margin="0 3px 0 0" type="tips"></uv-text></template>
							</uv-input>
						</uv-col>
					</uv-row>
				</view>
				
				<!-- 全国地区三级数据联动 -->
				<RxThreeLinkage ref="open_picker" v-on:customEvent="threeLinkageCustomEvent"></RxThreeLinkage>
				
				<view class="input_class"><uv-input border="bottom" v-model="pointsInfo.address"><template v-slot:prefix>
					<uv-text text="详细地址" margin="0 3px 0 0" type="tips"></uv-text></template>
				</uv-input></view>
				
			</view>
			<view class="form_submit_class">
				<uv-row>
					<uv-col span="6">
						<view style="width: 70%;margin-left: auto;margin-right: auto;">
							<uv-button :hairline="false" text="扫码" customTextStyle="color: #2c9c3c;font-size: 28rpx" @click="qrClick"></uv-button>
						</view>
					</uv-col>
					<uv-col span="6">
						<view style="width: 70%;margin-left: auto;margin-right: auto;">
							<uv-button :hairline="false" text="创建" color="#2c9c3c" customTextStyle="color: #ffffff;font-size: 28rpx" @click="createSubmit"></uv-button>
						</view>
					</uv-col>
				</uv-row>
			</view>
		</view>
		
		<view v-else>
			<view v-if="!handInfo">
				
				<view class="scan">
					<uv-button :hairline="false" text="扫码加入诊所" color="#2c9c3c" customTextStyle="color: #ffffff;font-size: 28rpx;" @click="scanClick"></uv-button>
				</view>
				
				<view v-if="userinfo.types === 1" class="hand_fill">
					<uv-text type="info" align="center" prefixIcon="order" iconStyle="font-size: 19px" text="创建诊所" @click="handClick"></uv-text>
				</view>
			</view>
			<view v-else>
				<view class="form_class">
					<view class="input_class"><uv-input border="bottom" v-model="pointsInfo.name"><template v-slot:prefix>
						<uv-text text="名称" margin="0 3px 0 0" type="tips"></uv-text></template>
					</uv-input></view>
					<view class="input_class"><uv-input border="bottom" v-model="pointsInfo.mobile" type="number" maxlength="11"><template v-slot:prefix>
						<uv-text text="电话" margin="0 3px 0 0" type="tips"></uv-text></template>
					</uv-input></view>
				</view>
				<view class="form_submit_class">
					<uv-row>
						<uv-col span="6">
							<view style="width: 70%;margin-left: auto;margin-right: auto;">
								<uv-button :hairline="false" text="返回" customTextStyle="color: #2c9c3c;font-size: 28rpx" @click="leftClick"></uv-button>
							</view>
						</uv-col>
						<uv-col span="6">
							<view style="width: 70%;margin-left: auto;margin-right: auto;">
								<uv-button :hairline="false" text="确定" color="#2c9c3c" customTextStyle="color: #ffffff;font-size: 28rpx" @click="handInfoSubmit"></uv-button>
							</view>
						</uv-col>
					</uv-row>
				</view>
			</view>
		</view>
		
		
		
	</view>
</template>

<script>
	import RxLogo from '@/components/RxLogo/RxLogo.vue'
	import RxThreeLinkage from '@/components/RxThreeLinkage/RxThreeLinkage.vue'
	export default {
		components: {
			RxLogo, RxThreeLinkage
		},
		data() {
			return {
				userinfo: {},
				hand: false,
				handInfo: false,
				types: null,
				pointsInfo: {
					clinic: null,
					name: null,
					mobile: null,
					address: null,
					// clinic: '李时珍诊所',
					// name: '李时珍',
					// mobile: '15622105281',
					// address: 'XXXXXXXXXXXXXX',
					addressProvince: null,
					addressCity: null,
					addressCounty: null
				},
				scanClinicId: ''
			}
		},
		destroyed() {
			this.$store.dispatch('clear_rx')
		},
		created() {
			this.userinfo = this.$store.state.userinfo
		},
		methods: {
			leftClick() {
				uni.navigateBack();
			},
			handClick() {
				this.hand = true
			},
			qrClick() {
				this.hand = false
			},
			parseQueryString(queryString) {  
			  const params = {};  
			  const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');  
			  for (let i = 0; i < pairs.length; i++) {  
			    const pair = pairs[i].split('=');  
			    params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');  
			  }  
			  return params;  
			},
			scanClick() {
				var _this = this
				uni.scanCode({
					success: function (res) {
						uni.showLoading()
						setTimeout(function() {
							console.log('扫码后获取到的诊所ID：' + res.result);
							const parsedParams = _this.parseQueryString(res.result.split('?')[1])
							_this.scanClinicId = parsedParams.clinicId
							if ( String(_this.userinfo.types) === parsedParams.types1 || String(_this.userinfo.types) === parsedParams.types0 || String(_this.userinfo.types) === parsedParams.types3 ) {
								if ( _this.userinfo.name && _this.userinfo.mobile ) {
									_this.handInfoSubmit()
								} else {
									_this.handInfo = true
									_this.hand = false
									uni.hideLoading()
								}
							} else if (String(_this.userinfo.types) === parsedParams.types2){
								if ( _this.userinfo.name && _this.userinfo.mobile ) {
									_this.handInfoSubmit()
								} else {
									_this.handInfo = true
									_this.hand = false
									uni.hideLoading()
								}
							} else {
								uni.showToast({ title: '非法扫码', icon: 'error' })
							}
						}, 1000)
					}
				});
				
			},
			handInfoSubmit() {
				uni.showLoading()
				var _this = this
				const neWpointsInfo = {
					name: _this.pointsInfo.name,
					mobile: _this.pointsInfo.mobile
				}
				const Empty = _this.areAllValuesNotEmpty(neWpointsInfo)
				if (Empty) {
					_this.$api.scan_code_clinic({
						clinicId: _this.scanClinicId,
						types: _this.userinfo.types,
						userId: _this.userinfo.userId,
						name: _this.handInfo?_this.pointsInfo.name:_this.userinfo.name,
						mobile: _this.handInfo?_this.pointsInfo.mobile:_this.userinfo.mobile,
					}).then((res) => {
						_this.$api.get_user_info({ userId: _this.userinfo.userId, types: _this.userinfo.types }).then((res) => {
							_this.userinfo.name = res.data.name
							_this.userinfo.mobile = res.data.mobile
							_this.userinfo.clinic = res.data.clinic
							_this.userinfo.clinic_data_all = res.data.clinic_data_all
							_this.userinfo.clinic_id_list = _this.userinfo.clinic_data_all.map(item => item._id)	// 使用map方法提取_id字段  
							_this.userinfo.self = res.data.self
							_this.$store.dispatch('set_userinfo', _this.userinfo)
							
							var pages = '/pages/patient/patient'
							if (_this.userinfo.types === 1) {
								pages = '/pages/medic/medic'
								const aa = getCurrentPages()
							} else if (_this.userinfo.types === 0) {
								pages = '/pages/nurse/nurse'
							} else if (_this.userinfo.types === 3) {
								pages = '/pages/visit/visit'
							}
							uni.reLaunch({
							    url: pages
							});
						}).catch((err) => {
							console.log(err)
							uni.showToast({ title: '服务错误', icon: 'error', duration: 3000 })
						})
					})
				} else {
					uni.showToast({
						icon: 'error',
						title: '完善数据'
					})
				}
			},
			PickerClick() {
				this.$refs.open_picker.open()
			},
			areAllValuesNotEmpty(pointsInfo) {
			    return Object.values(pointsInfo).every(value => value !== null && value !== undefined && value !== '');  
			},
			createSubmit() {
				const Empty = this.areAllValuesNotEmpty(this.pointsInfo)
				if (Empty) {
					const regExp = /^1[3456789]\d{9}$/; // 使用正则表达式进行校验
					if (!regExp.test(this.pointsInfo.mobile)) {
						uni.showToast({
							icon: 'error',
							title: '手机号码不正确'
						})
					} else {
						uni.showToast({ title: '诊所创建中', icon: 'loading', duration: 600000 })
						this.$api.login_create_clinic({
							data: this.pointsInfo,
							userId: this.$store.state.userinfo.userId,
							types: this.userinfo.types
						}).then((res)=> {
							this.userinfo.clinic = res.data.clinic
							this.userinfo.clinic_data_all = res.data.clinic_data_all
							this.userinfo.clinic_id_list = res.data.clinic_id_list
							this.userinfo.name = this.pointsInfo.name
							this.userinfo.mobile = this.pointsInfo.mobile
							this.$store.dispatch('set_rx', this.userinfo)
							setTimeout(function () {
								uni.reLaunch({ url: '/pages/medic/medic' })
								uni.hideTabBar()
							}, 1000);
						})
					}
				} else {
					uni.showToast({
						icon: 'error',
						title: '完善数据'
					})
				}
			}, 
			threeLinkageCustomEvent(data) {
				// 从子组件接收的省市区三级联动数据
				this.pointsInfo.addressProvince = data.addressProvince
				this.pointsInfo.addressCity = data.addressCity
				this.pointsInfo.addressCounty = data.addressCounty
			}
		}
	}
</script>

<style>
	.scan {
		width: 60%;
		margin-top: 25%;
		margin-left: auto; /* 左侧外边距自动调整为最大值 */
		margin-right: auto;/* 右侧外边距自动调整为最大值 */
	}
	
	.hand_fill {
		position: fixed; /* 或者使用 position: absolute; 根据你的布局需要 */
		bottom: 0; /* 使其固定在底部 */  
		left: 50%; /* 水平居中，需要配合 transform 使用 */  
		transform: translateX(-50%); /* 水平居中 */
		margin-bottom: 30px;
	}
	
	.form_class {
		width: 85%;
		margin-top: 15%;
		margin-left: auto; /* 左侧外边距自动调整为最大值 */
		margin-right: auto;/* 右侧外边距自动调整为最大值 */
	}
	
	.input_class {
		margin-bottom: 8px;
	}
	
	.form_submit_class {
		margin-top: 10%;
		margin-left: auto; /* 左侧外边距自动调整为最大值 */
		margin-right: auto;/* 右侧外边距自动调整为最大值 */
	}
</style>
